package com.cms.common.model.services.impl;


import com.cms.common.model.criteria.Criteria;
import com.cms.common.model.entity.Article;
import com.cms.common.model.repository.ArticleRepository;
import com.cms.common.model.services.ArticleService;
import com.cms.common.model.vo.RequestData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("ArticleService")
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleRepository articleRepository;


    @Override
    public Page<Article> getAllByPage(RequestData requestData) {
        Criteria<Article> criteria = new Criteria<>();
        requestData.setObjParams(criteria);
        Sort sort = Sort.by(Sort.Order.asc("updateTime"), Sort.Order.asc("id"));
        Pageable pageable = PageRequest.of(requestData.getPage() - 1, requestData.getPageSize(), sort);
        Page<Article> articles = articleRepository.findAll(criteria, pageable);
        return articles;
    }

    @Override
    public Article getById(Long id) {
        return articleRepository.findById(id).orElse(null);
    }

    @Override
    public Article addArticle(Article article) {
        return articleRepository.saveAndFlush(article);
    }

    @Override
    public void deleteArticle(Article article) {
        articleRepository.delete(article);
    }

    @Override
    public List<Article> getAll() {
        return articleRepository.findAll();
    }
}
